<?php

//necessário para todas as páginas do admin (facilitador)
include("defaultAdmin.php");

class CrudClientes {
	private $objUsrSession;
	private $objDaoPrincipal;
	private $objEstado;
	private $objCidade;
	
	private $menu1 = "clientes";
	private $classe_css = "clientes";

	private $DAO_principal = "Cliente";
	private $PK = "id_cliente";
	
	private $posGrid = array("Cliente", "Email", "Telefone", "Celular");
	private $posArrGrid = array("nome_cliente", "email_responsavel", "telefone_resid", "celular");
	private $titleGrid = "Clientes";
	private $titleForm = "Cliente";
	private $errosForm = array();
	
	private $camposObrigatorios = array(
		array("nome_cliente", "", "MENS_ERRO_NOME", "Campo Obrigatório."),
		array("telefone_resid", "", "MENS_ERRO_TEL_RES", "Campo Obrigatório.")
	);
	
	private function setItensRelacionados(){
		global $objCtrlSmarty;
		global $menu;
		
		$add = $list = array();
		$add["title"] = "Adicionar um novo:";
		$add["opcoes"][] = array("texto" => "Cliente", "link" => self::getLinkCadastrar());
		$objCtrlSmarty->assign("ADICIONAR",$add);
		
		$list["title"] = "Listar todos os:";
		$list["opcoes"][] = array("texto" => "Clientes", "link" => HttpUtil::getLink($menu, "pos1=".__CLASS__));
		$objCtrlSmarty->assign("LISTAR",$list);
	}
	
	private function getFormPadrao($id, $arrCampos = array()){
		global $menu;
		global $objCtrlSmarty;
		
		$arrOptions = Utf8Parsers::matrizUtf8Encode(self::getObjEstado()->getOptionsEstados());
		
		if(isset($id)){
			if(empty($arrCampos)){
				//busco os dados do banco
				$arrCampos = Utf8Parsers::arrayUtf8Encode(self::getObjDaoPrincipal()->buscaCampos($id));
				if(!empty($arrCampos["uf"])){
					$arrCidades = Utf8Parsers::matrizUtf8Encode(self::getObjCidade()->getCidadesByUf($arrCampos["uf"]));
				}
			}
		}
		
		$text[] = array(
					"label" => array("texto" => "Nome", "for" => "nome_cliente"),
					"campo" => array("name" => "nome_cliente", "value" => $arrCampos["nome_cliente"], "maxlength" => 60),
					"msg_erro" => $this->errosForm["MENS_ERRO_NOME"],
					"obrigatorio" => true
				);
		$text[] = array(
					"label" => array("texto" => "Telefone", "for" => "telefone_resid"),
					"campo" => array("name" => "telefone_resid", "value" => $arrCampos["telefone_resid"], "maxlength" => 14, "class" => "telefone"),
					"msg_erro" => $this->errosForm["MENS_ERRO_TEL_RES"],
					"obrigatorio" => true
				);
		$text[] = array(
					"label" => array("texto" => "Telefone Comercial", "for" => "telefone_comerc"),
					"campo" => array("name" => "telefone_comerc", "value" => $arrCampos["telefone_comerc"], "maxlength" => 14, "class" => "telefone"),
					"msg_erro" => $this->errosForm["MENS_ERRO_TEL_COM"]
				);
		$text[] = array(
					"label" => array("texto" => "Celular", "for" => "celular"),
					"campo" => array("name" => "celular", "value" => $arrCampos["celular"], "maxlength" => 14, "class" => "telefone"),
					"msg_erro" => $this->errosForm["MENS_ERRO_CELULAR"]
				);
		$text[] = array(
					"label" => array("texto" => "CPF", "for" => "cpf"),
					"campo" => array("name" => "cpf", "value" => $arrCampos["cpf"], "maxlength" => 11),
					"msg_erro" => $this->errosForm["MENS_ERRO_CPF"]
				);
		$text[] = array(
					"label" => array("texto" => "CNPJ", "for" => "cnpj"),
					"campo" => array("name" => "cnpj", "value" => $arrCampos["cnpj"], "maxlength" => 15),
					"msg_erro" => $this->errosForm["MENS_ERRO_CNPJ"]
				);
		$text[] = array(
					"label" => array("texto" => "Nome Responsável", "for" => "nome_responsavel"),
					"campo" => array("name" => "nome_responsavel", "value" => $arrCampos["nome_responsavel"], "maxlength" => 60),
					"msg_erro" => $this->errosForm["MENS_ERRO_NOME_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Setor Responsável", "for" => "setor_responsavel"),
					"campo" => array("name" => "setor_responsavel", "value" => $arrCampos["setor_responsavel"], "maxlength" => 60),
					"msg_erro" => $this->errosForm["MENS_ERRO_SETOR_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Email Responsável", "for" => "email_responsavel"),
					"campo" => array("name" => "email_responsavel", "value" => $arrCampos["email_responsavel"], "maxlength" => 60),
					"msg_erro" => $this->errosForm["MENS_ERRO_EMAIL_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Telefone Responsável", "for" => "telefone_responsavel"),
					"campo" => array("name" => "telefone_responsavel", "value" => $arrCampos["telefone_responsavel"], "maxlength" => 14, "class" => "telefone"),
					"msg_erro" => $this->errosForm["MENS_ERRO_TEL_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Ramal Responsável", "for" => "ramal_responsavel"),
					"campo" => array("name" => "ramal_responsavel", "value" => $arrCampos["ramal_responsavel"], "maxlength" => 15),
					"msg_erro" => $this->errosForm["MENS_ERRO_RAMAL_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Celular Responsável", "for" => "celular_responsavel"),
					"campo" => array("name" => "celular_responsavel", "value" => $arrCampos["celular_responsavel"], "maxlength" => 14, "class" => "telefone"),
					"msg_erro" => $this->errosForm["MENS_ERRO_CEL_RESP"]
				);
		$text[] = array(
					"label" => array("texto" => "Logradouro", "for" => "logradouro"),
					"campo" => array("name" => "logradouro", "value" => $arrCampos["logradouro"], "maxlength" => 60),
					"msg_erro" => $this->errosForm["MENS_ERRO_LOGRADOURO"]
				);
		$text[] = array(
					"label" => array("texto" => "Número", "for" => "numero"),
					"campo" => array("name" => "numero", "value" => $arrCampos["numero"], "maxlength" => 10),
					"msg_erro" => $this->errosForm["MENS_ERRO_NUMERO"]
				);
		$text[] = array(
					"label" => array("texto" => "Complemento", "for" => "complemento"),
					"campo" => array("name" => "complemento", "value" => $arrCampos["complemento"], "maxlength" => 15),
					"msg_erro" => $this->errosForm["MENS_ERRO_COMPLEMENTO"]
				);
		$text[] = array(
					"label" => array("texto" => "Referência", "for" => "referencia"),
					"campo" => array("name" => "referencia", "value" => $arrCampos["referencia"], "maxlength" => 100),
					"msg_erro" => $this->errosForm["MENS_ERRO_REFERENCIA"]
				);
		$textarea[] = array(
					"label" => array("texto" => "Observações", "for" => "observacao"),
					"campo" => array("name" => "observacao", "value" => $arrCampos["observacao"]),
					"msg_erro" => $this->errosForm["MENS_ERRO_OBSERVACAO"]
				);
		$arrTipoCliente = array(
				array("value"=>CLIENTE_PF, "text"=>"Pessoa Física"), 
				array("value"=>CLIENTE_Pj, "text"=>"Pessoa Jurídica"), 
		);
		
		$arrCampos["tipo_cliente"] = $arrCampos["tipo_cliente"] == ""?CLIENTE_PF:$arrCampos["tipo_cliente"];
		$radio[] = array( 
						"label" => array("texto" => "Tipo Cliente", "for" => "tipo_cliente"),
						"campo" => array("name" => "tipo_cliente", "value" => $arrCampos["tipo_cliente"], "valores" => $arrTipoCliente, "onchange" => "verificaCliente(this.value);")
					);
		$select[] = array( 
						"label" => array("texto" => "UF", "for" => "uf"),
						"campo" => array("name" => "uf", "value" => $arrCampos["uf"], "valores" => $arrOptions, "onchange" => "getCidades(this.value);")
					);
		if(!empty($arrCampos["uf"])){
			$pos = "valores";
			$val = $arrCidades;
		}else{
			$pos = "disabled";
			$val = true;
		}
		
		$select[] = array( 
						"label" => array("texto" => "Cidade", "for" => "cidade"),
						"campo" => array("name" => "cidade", "value" => $arrCampos["cidade"], $pos => $val)
					);
		$hidden[] = array(
						"campo" => array("type" => "hidden", "name" => "id_cliente", "value" => $arrCampos["id_cliente"])
					);
		$ordem = array("tipo_cliente", "nome_cliente", "telefone_resid", "telefone_comerc", "celular", 
		"|abreClass|pf", "cpf", "|fechaClass|pf", 
		"|abreClass|pj", 
			"cnpj", "nome_responsavel", "setor_responsavel", "email_responsavel", 
			"telefone_responsavel", "ramal_responsavel", "celular_responsavel", 
		"|fechaClass|pj", 
		"uf", "cidade", "logradouro", "numero", "complemento", "referencia", "observacao");
						
		$camposForm = array("ordem" => $ordem,"text" => $text, "select" => $select, "hidden" => $hidden, "textarea" => $textarea, "radio" => $radio);
		
		$strJsPag = setScriptMenu($this->menu1, $this->classe_css, true);
		$strJsPag .= "<script type=\"text/javascript\">
		jQuery(document).ready(function(){
			jQuery('.telefone').mask('(99) 9999-9999');
			jQuery('#cpf').mask('999.999.999-99');
			jQuery('#cnpj').mask('99.999.999/9999-99');
			";
		if($arrCampos["tipo_cliente"] == CLIENTE_PF){
			$strJsPag .= " jQuery('.pj').hide(); ";
		}else{
			$strJsPag .= " jQuery('.pf').hide(); ";
		}
		$strJsPag .= " });
		</script>";
		$objCtrlSmarty->assign("JS_PAGE",$strJsPag);
		
		//seto no formulário os campos
		$objCtrlSmarty->assign(CAMPOS_FORM,$camposForm);
		$objCtrlSmarty->assign("TITLE", (($id)?"Editar ":"Cadastrar ").$this->titleForm);
		self::setItensRelacionados();
		self::setLinksPadrao();
		$objCtrlSmarty->assign("CONTEUDO_ADMIN",$objCtrlSmarty->fetch(TPLS_FILE."admin/formRegistros.tpl"));
	}
	
	private function getObjEstado() {
        if ($this->objEstado == null) {
            $this->objEstado = new Estado();
        }
        return $this->objEstado;
    }
	private function getObjCidade() {
        if ($this->objCidade == null) {
            $this->objCidade = new Cidade();
        }
        return $this->objCidade;
    }
	
    /* METODOS GERAIS */
    
	function __construct(){
		global $objCtrlSmarty;
		confereSessao();
		setScriptMenu($this->menu1, $this->classe_css);
		$id = getId(); 
		$objCtrlSmarty->assign($this->PK,$id);
		$view = $_GET["a"];
		switch ($view){
			case 'form':
				self::getFormPadrao($id);
				break;
			case 'post':
				self::salvaDados($id);
				break;
			case 'excluir':
				self::getObjDaoPrincipal()->deletar($id);
				HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=4"));
				break;
			case 'lista':
			default:
				self::getListaDados();
				break;
		}
	}
	
	private function salvaDados(){
		global $menu;
		global $objCtrlSmarty;
		
		try{
			//validação caso o javascript esteja desabilitado
			$arrErros = array();
			foreach ($this->camposObrigatorios as $campo){
				//caso apresente erro já seto no template o erro.
				if($_POST[$campo[0]] == $campo[1]) $this->errosForm[$campo[2]] = $campo[3];
			}
			//fim validação dos dados
			
			if(count($arrErros) == 0){
				$id = getId($_POST[$this->PK]);
				self::getObjDaoPrincipal()->alterar($id,$_POST,$_FILES);
				HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=3"));
			}else{
				//caso tenha algum erro exibo o form novamente apresentado o erro.
				self::getFormPadrao($id);
			}
		}catch(CustonException $e){
			HttpUtil::vaiPara(HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", "msg=5"));
		}
	}
		
	private function getListaDados(){
		global $menu;
		global $objCtrlSmarty;

		$ordenar = FormataString::retiraCharsInvalidos(trim($_GET["ord"]));
		self::getObjDaoPrincipal()->setCampoSessaoOrdenacao($this->classe_css);
		if(!empty($ordenar))
			$_SESSION["order_".$this->classe_css] = $ordenar;
		
		$pagAtual = intval(FormataString::retiraCharsInvalidos(trim($_GET["pag"])));
		$arrDados = Utf8Parsers::matrizUtf8Encode(self::getObjDaoPrincipal()->getListaRegistros($pagAtual, addslashes($_POST["busca"])));
		$count = self::getObjDaoPrincipal()->getCountListaRegistros(addslashes($_POST["busca"]));
		
		
 		if ($count > NUM_ELEMENTOS_GRID) {
            $totPags = ceil($count / NUM_ELEMENTOS_GRID);
            $objCtrlSmarty->assign("NUMPAGS_GRID", $totPags);
            $objCtrlSmarty->assign("NUMREGS_GRID", $count);
            $objCtrlSmarty->assign("PAGATUAL_GRID", ($pagAtual +1));
            $objCtrlSmarty->assign("PAGINACAO", ($totPags > 1) ? true : false);
            $busca = (!empty($_POST["busca"]))?"busca=".addslashes($_POST["busca"]):"";
            $objCtrlSmarty->assign("LINK_ATUALPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca));
            $objCtrlSmarty->assign("LINK_PRIMEIRAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=nulo"));
            $objCtrlSmarty->assign("LINK_PAGANTERIOR", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($pagAtual-1)));
            $objCtrlSmarty->assign("LINK_PROXIMAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($pagAtual+1)));
            $objCtrlSmarty->assign("LINK_ULTIMAPAG", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "pag=".($totPags-1)));
        }
		
		foreach ($arrDados as $key => $person){
        	$arrDados[$key]["editar"] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=form", "id=".$person[$this->PK]);
        	$arrDados[$key]["excluir"] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=excluir", "id=".$person[$this->PK]);
        }
        
        $arrOrder = array();
        foreach ($this->posArrGrid as $col){
        	$arrOrder[] = HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista", $busca, "ord=".$col);
        }
        $objCtrlSmarty->assign("POSITIONS_ORDER", $arrOrder);
        $objCtrlSmarty->assign("ORDERNAR_POR", $_SESSION["order_".$this->classe_css]);
        
        $objCtrlSmarty->assign("POSITIONS", $this->posGrid);
        $objCtrlSmarty->assign("POSITIONS_FIELDS", $this->posArrGrid);
        $objCtrlSmarty->assign("TITLE", $this->titleGrid);
        
        $objCtrlSmarty->assign("arrRegistros", $arrDados);
        $objCtrlSmarty->assign("TERMO_BUSCA", str_replace("\\\"", "&quot;", addslashes($_POST["busca"])));
        self::setLinksPadrao();
		$objCtrlSmarty->assign("CONTEUDO_ADMIN",$objCtrlSmarty->fetch(TPLS_FILE."admin/listaRegistros.tpl"));
	}
		
	private function getLinkCadastrar(){
		global $menu;
		return HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=form");
	}
		
	private function setLinksPadrao(){
		global $objCtrlSmarty;
		global $menu;
		
		$objCtrlSmarty->assign("LINK_BUSCAR", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=lista"));
        $objCtrlSmarty->assign("LINK_CADASTRAR", self::getLinkCadastrar());
        $objCtrlSmarty->assign("LINK_ACTION", HttpUtil::getLink($menu, "pos1=".__CLASS__, "a=post"));
		$objCtrlSmarty->assign("LINK_VOLTAR", HttpUtil::getLink($menu, "pos1=".__CLASS__));
	}
	
	private function getObjDaoPrincipal() {
        if ($this->objDaoPrincipal == null) {
            $this->objDaoPrincipal = new $this->DAO_principal();
        }
        return $this->objDaoPrincipal;
    }

}
?>